/**
 * 2013-10-15
 * 下午1:17:50
 */
package com.hunlian.makelove;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.hunlian.makelove.common.AppConfig;
import com.hunlian.makelove.common.AppUtils;
import com.hunlian.makelove.common.ContextUtils;
import com.hunlian.makelove.common.DateUtils;
import com.hunlian.makelove.tools.LogTools;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * 调用系统相机或选择相册查看图片
 *
 * @author zj
 * @time 2013-10-15下午1:41:44
 */
public class TakeCameraOrAlbum {

    public String IdentityPicPath;
    public String frontlastPicName = "", backlastPicName = "";
    public final int FrontCode = 1, BackCode = 2;
    public final int TakePicFrontCode = 3, TakePicBackCode = 4;
    public final int SelectPicFrontCode = 5, SelectPicBackCode = 6;


    /**
     * 操作判断标志符 1表示调用相机拍照，2表示从相册选择照片
     */
    public final int TakePics = 1, SelectAlbum = 2;
    /**
     * 里面存放了从网络下载和相机拍照和从相册选择的在View中显示的所有图片的绝对路径
     */
    public List<String> picList = new ArrayList<String>();
    /**
     * 图片与图片之间的水平间隔
     */
    public final int PicHorizontalSpacingSize = 8;
    /*
     * 用来存放图片名及bitmap的HashMap
     */
    private Map<String, Bitmap> map = new HashMap<String, Bitmap>();

    /**
     * 网络图片的url地址数组
     */
    private String[] urls;
    /**
     * 网络下载的图片名称头几个字符的标志
     */
    private final String HttpPicTag = "http_";

    private final String Dir = "HLW_Pics";

    public List<String> getPicList() {
        return picList;
    }


    /**
     * 处理用&符号隔开的多个图片url地址并通过网络获取这些图片
     *
     * @param activity
     * @param dirPath
     * @param url
     */
    public void handlePicUrls(Activity activity, String dirPath, String url) {

        if (url.equals(""))
            urls = new String[]{};
        else {
            //分隔url
            urls = url.split("&");
        }
        //清空
        picList.clear();
        //初始化占位图片
        for (int i = 0; i < urls.length; i++) {
            if (picList.contains(urls[i])) continue;
            map.put(urls[i], null);
            picList.add(urls[i]);
        }

        for (int i = 0; i < urls.length; i++) {
            DownloadImage(dirPath, urls[i]);
        }

    }


    class BitmapWorkerTask extends AsyncTask<String, ImageView, Bitmap> {

        private String imageUrl;
        private String dirPath;
        private String fileName;

        public BitmapWorkerTask(String dirPath, String imageUrl) {
            super();
            this.dirPath = dirPath;
            this.imageUrl = imageUrl;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            imageUrl = params[0];
            // 在后台开始下载图片
            Bitmap bitmap = downloadBitmap(params[0]);
            Random random = new Random(10000);
            if (bitmap != null) {
                //创建文件夹
                ContextUtils.makeDirs(dirPath);
                // 图片下载完成后保存到本地
                fileName = dirPath + HttpPicTag + DateUtils.getLocalLongDate14() + "x" + random.nextInt() + ".jpg";
                saveBitmap2file(bitmap, fileName);
                //将url换成本地保存的图片地址
                if (picList.contains(imageUrl)) {
                    picList.set(picList.indexOf(imageUrl), fileName);
                }
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
            // 根据Tag找到相应的ImageView控件，将下载好的图片显示出来。

            if (bitmap != null) {
                //将url换成本地保存的图片地址
                map.remove(imageUrl);
                map.put(fileName, bitmap);

                //下载完成
                downloadOverOneFile(fileName);
            }

        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                con.setDoInput(true);
                //con.setDoOutput(true);
                con.setRequestMethod("GET");
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }

    }

    /**
     * 下载完一个文件后的回调函数，子类要重写这个方法
     *
     * @param fileName 下载好的图片的名字
     * @author: Administrator
     * @time: 2013-10-25下午1:33:39
     */
    public void downloadOverOneFile(String fileName) {

    }


    /**
     * 开启下载异步线程
     *
     * @param imageUrl 下载地址
     */
    public void DownloadImage(String dirPath, String imageUrl) {
        BitmapWorkerTask task = new BitmapWorkerTask(dirPath, imageUrl);
        task.execute(imageUrl);
    }


    /**
     * 将bitmap保存为图片
     *
     * @param bmp
     * @param filename
     * @return 成功保存返回true
     */
    public boolean saveBitmap2file(Bitmap bmp, String filename) {
        if (bmp == null) return false;
        CompressFormat format = CompressFormat.JPEG;
        int quality = 50;
        OutputStream stream;
        try {
            stream = new FileOutputStream(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            AppApplication.errorTrack.append("TakeCameraOrAlbum.saveBitmap2file : "+filename+" 这个文件找不到"+"\n");
            Log.e("konly",filename+" 这个文件找不到");
            return false;
        }

        boolean boo = bmp.compress(format, quality, stream);
        bmp.recycle();
        return boo;
    }

    /**
     * 将bitmap保存为图片
     *
     * @param bmp
     * @param filename
     * @return 成功保存返回true
     */
    public boolean saveBitmap2fileAfterClear(Bitmap bmp, String filename) {
        CompressFormat format = CompressFormat.JPEG;
        int quality = 100;
        OutputStream stream = null;
        try {
            stream = new FileOutputStream(filename);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        boolean boo = bmp.compress(format, quality, stream);
        bmp.recycle();
        bmp = null;
        return boo;
    }


    /**
     * 调用相机拍照
     *
     *   返回拍照的图片的绝对路径
     */
    public String takePics(Activity activity, String dirPath) {
        //创建文件夹
        ContextUtils.makeDirs(dirPath);
        String savePicName = DateUtils.getLocalLongDate14() + ".jpg";
        String picPath = dirPath + savePicName + ".jpg";
        File myCaptureFile = new File(picPath);

        Uri outputFileUri = Uri.fromFile(myCaptureFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                outputFileUri);
        activity.startActivityForResult(intent, TakePics);
        return picPath;
    }

    /**
     * 调用相机拍照
     *
     * return 返回拍照的图片的绝对路径
     */
    public String takePics(Activity activity, String picName, String dirPath) {
        //创建文件夹
        ContextUtils.makeDirs(dirPath);
        String picPath = dirPath + picName + ".jpg";
        File myCaptureFile = new File(picPath);

        Uri outputFileUri = Uri.fromFile(myCaptureFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                outputFileUri);
        activity.startActivityForResult(intent, TakePics);
        return picPath;
    }

    /**
     * 调用相机拍照
     *
     * @param activity   上下文
     * @param dirPath    图片保存的目录
     * @param picName    不带后缀的图片的名字
     * @param requseCode 请求码
     *  return     返回拍照的图片的绝对路径
     * @Author zj
     */
    public String takePics(Activity activity, String dirPath, String picName, int requseCode) {
        //创建文件夹
        ContextUtils.makeDirs(dirPath);
        String picPath = dirPath + picName + ".jpg";
        File myCaptureFile = new File(picPath);

        AppApplication.errorTrack.delete(0,AppApplication.errorTrack.length());
        AppApplication.errorTrack.append("TakeCameraOrAlbum.takePics: "+"拍照 要保存的图片的路径："+myCaptureFile.getAbsolutePath()+"\n");
        Uri outputFileUri = Uri.fromFile(myCaptureFile);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,
                outputFileUri);
        activity.startActivityForResult(intent, requseCode);
        return picPath;
    }

    /**
     * 成功保存返回true
     *
     * @author zealjiang
     * @time 2016/5/8 17:36
     */
    public boolean saveBitmapToFile(Bitmap bitmap, String dirPath, String picName) {
        //创建文件夹
        ContextUtils.makeDirs(dirPath);
        String picPath = dirPath + picName + ".jpg";

        return saveBitmap2file(bitmap, picPath);
    }


    /**
     * 调用系统相册
     */
    public void takeSysPhotoAlbum(Activity activity, int requseCode) {


        String status = Environment.getExternalStorageState();
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            activity.startActivityForResult(intent, requseCode);
        } else {

            AppApplication.errorTrack.append("TakeCameraOrAlbum.takeSysPhotoAlbum: "+"从相册选择 没有储存卡："+"\n");
            Toast.makeText(activity, "没有储存卡", Toast.LENGTH_LONG).show();
        }

    }




    /**
     * 调用系统相机成功拍照后，从Intent中取到照片信息并处理
     *
     * @param data
     * @param picPath
     * @author: zj
     * @time: 2013-10-14上午11:50:15
     */
    public boolean handleTakenPic(Intent data, String picPath) {
        Bitmap bitmap;
        if (data != null) {
            Bundle bundle = data.getExtras();
            // 获取相机返回的数据，并转换为图片格式
            bitmap = (Bitmap) bundle.get("data");
        } else {
            bitmap = picFileToBitmap(picPath);
        }

        if(bitmap==null){
            return false;
        }

        int degree = readPictureDegree(picPath);
        // 旋转图片
        Bitmap newBitmap = rotateBitmap(bitmap, degree);
        if (newBitmap == null) {
            // 保存图片
            saveBitmap2file(bitmap, picPath);
        } else {
            // 保存图片
            saveBitmap2file(newBitmap, picPath);
        }
        return true;
    }

    /**
     * 旋转bitmap
     *
     * @param bitmap
     * @param degrees 旋转的角度
     * @return 旋转后的bitmap
     * @time: 2013-10-14上午11:42:52
     */
    public Bitmap rotateBitmap(Bitmap bitmap, float degrees) {
        if (bitmap == null)
            return bitmap;

        Bitmap bMapRotate;

        Matrix matrix = new Matrix();
        matrix.reset();
        matrix.postRotate(degrees);
        try {
            bMapRotate = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
                    bitmap.getHeight(), matrix, true);
        } catch (OutOfMemoryError e) {
            bMapRotate = bitmap;
        }

        return bMapRotate;

    }


    /**
     * 处理从系统相册选择图片
     *
     * @param activity     上下文
     * @param singleWidget 只能显示一张图片的单个控件
     * @param dirPath      图片文件所在的目录
     * @param data         onActivityResult中的Intent携带了选中图片的信息
     */
    protected String handleSelectedSysPhoto(Activity activity, ImageView singleWidget, String dirPath, Intent data) {

        String picPath = "";
        Uri selectedImage = data.getData();
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        Cursor c = activity.getContentResolver().query(selectedImage,
                filePathColumns, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePathColumns[0]);
        String picturePath = c.getString(columnIndex);
        c.close();

        //判断picturePath中是否有path,如果没有就拷贝
        if (!picturePath.toLowerCase().contains(dirPath.toLowerCase())) {
            int num = picturePath.lastIndexOf("/");
            String fromFile = picturePath.substring(num + 1, picturePath.length());
            ContextUtils.copyFile(new File(picturePath),
                    new File(dirPath + fromFile), true);
            refreshSysPhotoAlbum(activity, dirPath + fromFile);
            loadShowIdentity(activity, singleWidget, dirPath + fromFile,false);
            picPath = dirPath + fromFile;
        } else {
            loadShowIdentity(activity, singleWidget, picturePath,false);
            picPath = picturePath;
        }

        return picPath;
    }

    /**
     * 处理从系统相册选择图片
     *
     * @param activity     上下文
     * @param singleWidget 只能显示一张图片的单个控件
     * @param dirPath      图片文件所在的目录
     * @param fileName     图片文件的名字不含目录名和后缀名
     * @param data         onActivityResult中的Intent携带了选中图片的信息
     * @return 返回所选图片拷贝后所在的路径
     */
    public String handleSelectedSysPhoto(Activity activity, ImageView singleWidget, String dirPath, String fileName, Intent data) {

        String picPath = "";
        Uri selectedImage = data.getData();
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        Cursor c = activity.getContentResolver().query(selectedImage,
                filePathColumns, null, null, null);
        c.moveToFirst();
        int columnIndex = c.getColumnIndex(filePathColumns[0]);
        String picturePath = c.getString(columnIndex);
        c.close();

        //判断picturePath中是否有path,如果没有就拷贝
        if (!picturePath.toLowerCase().contains(dirPath.toLowerCase())) {
            String fromFile = fileName + ".jpg";
            ContextUtils.copyFile(new File(picturePath),
                    new File(dirPath + fromFile), true);
            refreshSysPhotoAlbum(activity, dirPath + fromFile);
            loadShowIdentity(activity, singleWidget, dirPath + fromFile,false);
            picPath = dirPath + fromFile;
        } else {
            loadShowIdentity(activity, singleWidget, picturePath,false);
            picPath = picturePath;
        }

        return picPath;
    }

    /**
     * 处理从系统相册选择图片
     *
     * @param activity 上下文
     * @param data     onActivityResult中的Intent携带了选中图片的信息
     */
    public String handleSelectedSysPhoto(Activity activity,Intent data) {

        if(data==null){
            Toast.makeText(activity,"请从图库选择试试",Toast.LENGTH_SHORT).show();
            LogTools.e(TakeCameraOrAlbum.class.getName()+"Intent data==null");
            return "";
        }
        Uri selectedImage = data.getData();
        String[] filePathColumns = {MediaStore.Images.Media.DATA};
        Cursor c = activity.getContentResolver().query(selectedImage,
                filePathColumns, null, null, null);

        String picturePath = "";
        if(null!=c){
            int columnIndex = c.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            //int columnIndex = c.getColumnIndex(filePathColumns[0]);
            c.moveToFirst();
            picturePath = c.getString(columnIndex);
            c.close();
        }else{
            picturePath = selectedImage.getPath();
        }

        return picturePath;
    }


    /**
     *
     * 将图片srcPath复制到dirPath目录下，并命名其名称为fileName
     * @param srcPath  图片文件全路径
     * @param dirPath  图片文件所在的目录
     * @param fileName 图片文件的名字不含目录名和后缀名
     */
    public String copyPhoto(String srcPath, String dirPath, String fileName) {

        String picPath = "";

        //判断dirPath文件夹下是否存在选择的图片
        String picName = new File(srcPath).getName();
        File dirF = new File(dirPath);
        String toFile = fileName + ".jpg";

        if(!dirF.exists()){//如果目录不存在就复制
            ContextUtils.copyFile(new File(srcPath),
                    new File(dirPath + toFile), true);
        }else{
            //判断此目录下是否有选中的图片
            String[] names = dirF.list();
            boolean isHave = false;
            for (int i = 0; i < names.length; i++) {
                if(names[i].equals(picName)){
                    isHave = true;
                    break;
                }
            }
            if(!isHave){
                ContextUtils.copyFile(new File(srcPath),
                        new File(dirPath + toFile), true);
            }
        }

        picPath = dirPath + toFile;
        return picPath;
    }


    /**
     * 拍照完成后，刷新系统相册，将刚拍完的照片加载到系统相册里
     */
    protected void refreshSysPhotoAlbum(Context context, String picPath) {
        MediaScannerConnection.scanFile(context, new String[]{picPath},
                new String[]{"image/jpeg"}, new MediaScannerConnection.OnScanCompletedListener() {

                    @Override
                    public void onScanCompleted(String path, Uri uri) {

                    }

                });
    }


    /**
     * 将一个图片文件转成一个bitmap
     * @author zj
     * @param filePath 图片的绝对路径
     * @return 如果图片文件存在并且是一张图片文件返回bitmap，否则返回null
     */
/*	public Bitmap picFileToBitmap(String filePath){

		if(new File(filePath).exists())
			return BitmapFactory.decodeFile(filePath);
		else 
			return null;
	}*/


    /**
     * 将一个图片文件转成一个bitmap
     *
     * @param filePath 图片的绝对路径
     * @return 如果图片文件存在并且是一张图片文件返回bitmap，否则返回null
     * @author zj
     */
    public Bitmap picFileToBitmap(String filePath) {
        File file = new File(filePath);
        FileInputStream fs = null;
        try {
            fs = new FileInputStream(file);
            if (fs == null){
                return null;
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        Bitmap bmp = null;
        if (fs != null) {
            try {
                if(AppConfig.SCREEN_WIDTH!=0){
                    bmp = compressPicToBitmap(filePath,AppConfig.SCREEN_WIDTH,AppConfig.SCREEN_WIDTH);
                }else{
                    bmp = compressPicToBitmap(filePath,1080,1080);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (fs != null)
                    try {
                        fs.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
            }
        }
        return bmp;
    }

    /**
     * 加载本地图片
     * http://bbs.3gstdy.com
     *
     * @param url
     * @return
     */
    public static Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Bitmap转成drawable
     *
     * @param bitmap
     * @return drawable
     * @author: zj
     * @time: 2013-10-24下午2:16:39
     */
    public Drawable bitmapToDrawable(Bitmap bitmap) {
        Drawable drawable = null;
        if (bitmap != null)
            drawable = new BitmapDrawable(bitmap);
        return drawable;
    }

    /**
     * 将drawable转换成bitmap
     *
     * @param drawable
     * @return
     * @author: zj
     * @time: 2013-11-7下午3:04:45
     */
    public Bitmap drawableToBitmap(Drawable drawable) {
        // 取 drawable 的长宽
        int w = drawable.getIntrinsicWidth();
        int h = drawable.getIntrinsicHeight();

        // 取 drawable 的颜色格式
        Bitmap.Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                : Bitmap.Config.RGB_565;
        // 建立对应 bitmap
        Bitmap bitmap = Bitmap.createBitmap(w, h, config);
        // 建立对应 bitmap 的画布
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, w, h);
        // 把 drawable 内容画到画布中
        drawable.draw(canvas);
        return bitmap;
    }

    /**
     * 加载并显示图片到控件中
     *
     * @param context 上下文
     * @param view    显示图片的控件
     * @param picPath 图片的绝对路径
     * @author: zj
     * @time: 2013-10-24下午2:21:34
     */
    public void loadShowIdentity(Context context, ImageView view, String picPath,boolean isRound) {
        view.setImageDrawable(null);
        handleTakenPic(null, picPath);
        //拍照完成后，刷新系统相册，将刚拍完的照片加载到系统相册里
        refreshSysPhotoAlbum(context, picPath);
        //刷新本地相册
        ContextUtils.refreshLocalPhotoAlbum(context, IdentityPicPath);

        //将拍的照片加载到view中
        //Bitmap bitmap = picFileToBitmap(picPath);//根据图片的路径得到图片的bitmap
        //Bitmap bitmap = compressPicToBitmap(picPath,80);//根据图片的路径得到压缩后的图片的bitmap
        //Bitmap bitmap = compressPicToBitmap(picPath,200,200);//根据图片的路径得到压缩后的图片的bitmap
        Bitmap bitmap = getScaledBitmap(picPath, 200, 200);

        if(bitmap==null){
            Toast.makeText(context,"请重新选择一张图片试试",Toast.LENGTH_SHORT).show();
            if(isRound) {
                view.setImageResource(R.drawable.icon_head);
            }else{
                view.setImageResource(R.drawable.add_pic);
            }
            return;
        }
        if(isRound){
            //将点像设置为圆的
            bitmap = AppUtils.toRoundBitmap(bitmap);
        }
        //加载图片到view
        view.setImageDrawable(bitmapToDrawable(bitmap));
    }

    public boolean handlePic(Context context, String picPath) {
        boolean boo = handleTakenPic(null, picPath);
        //拍照完成后，刷新系统相册，将刚拍完的照片加载到系统相册里
        refreshSysPhotoAlbum(context, picPath);
        //刷新本地相册
        ContextUtils.refreshLocalPhotoAlbum(context, IdentityPicPath);

        return boo;
    }

    public void loadPic(Context context, ImageView view, String picPath) {
		
/*		int degree = readPictureDegree(picPath);
		
		Bitmap bitmap = BitmapFactory.decodeFile(picPath);
		// 旋转图片
		Bitmap newBitmap = rotateBitmap(bitmap, degree);
		
		bitmap.recycle();*/

        Bitmap bitmap = BitmapFactory.decodeFile(picPath);
        //加载图片到view
        view.setImageBitmap(bitmap);
    }

    private static int getResizedDimension(int maxPrimary, int maxSecondary, int actualPrimary,
                                           int actualSecondary) {
        // If no dominant value at all, just return the actual.
        if (maxPrimary == 0 && maxSecondary == 0) {
            return actualPrimary;
        }

        // If primary is unspecified, scale primary to match secondary's scaling ratio.
        if (maxPrimary == 0) {
            double ratio = (double) maxSecondary / (double) actualSecondary;
            return (int) (actualPrimary * ratio);
        }

        if (maxSecondary == 0) {
            return maxPrimary;
        }

        double ratio = (double) actualSecondary / (double) actualPrimary;
        int resized = maxPrimary;
        if (resized * ratio > maxSecondary) {
            resized = (int) (maxSecondary / ratio);
        }
        return resized;
    }

    /**
     * Returns the largest power-of-two divisor for use in downscaling a bitmap
     * that will not result in the scaling past the desired dimensions.
     *
     * @param actualWidth   Actual width of the bitmap
     * @param actualHeight  Actual height of the bitmap
     * @param desiredWidth  Desired width of the bitmap
     * @param desiredHeight Desired height of the bitmap
     */
    private static int findBestSampleSize(
            int actualWidth, int actualHeight, int desiredWidth, int desiredHeight) {
        double wr = (double) actualWidth / desiredWidth;
        double hr = (double) actualHeight / desiredHeight;
        double ratio = Math.min(wr, hr);
        float n = 1.0f;
        while ((n * 2) <= ratio) {
            n *= 2;
        }

        return (int) n;
    }

    /**
     * 将图片压缩为指定宽高的Bitmap
     *
     * @param imagePath
     * @param maxWidth
     * @param maxHeight
     * @return
     */
    public static Bitmap getScaledBitmap(String imagePath, int maxWidth, int maxHeight) {
        BitmapFactory.Options decodeOptions = new BitmapFactory.Options();
        Bitmap bitmap = null;
        // If we have to resize this image, first get the natural bounds.
        decodeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(imagePath, decodeOptions);
        int actualWidth = decodeOptions.outWidth;
        int actualHeight = decodeOptions.outHeight;

        // Then compute the dimensions we would ideally like to decode to.
        int desiredWidth = getResizedDimension(maxWidth, maxHeight,
                actualWidth, actualHeight);
        int desiredHeight = getResizedDimension(maxHeight, maxWidth,
                actualHeight, actualWidth);

        // Decode to the nearest power of two scaling factor.
        decodeOptions.inJustDecodeBounds = false;
        // decodeOptions.inPreferQualityOverSpeed = PREFER_QUALITY_OVER_SPEED;
        decodeOptions.inSampleSize =
                findBestSampleSize(actualWidth, actualHeight, desiredWidth, desiredHeight);
        Bitmap tempBitmap = BitmapFactory.decodeFile(imagePath, decodeOptions);
        // If necessary, scale down to the maximal acceptable size.
        if (tempBitmap != null && (tempBitmap.getWidth() > desiredWidth ||
                tempBitmap.getHeight() > desiredHeight)) {
            bitmap = Bitmap.createScaledBitmap(tempBitmap,
                    desiredWidth, desiredHeight, true);
            Log.i("TakeCameraOrAlbum ","desiredWidth: "+desiredWidth);
            Log.i("TakeCameraOrAlbum ","desiredHeight: "+desiredHeight);
            tempBitmap.recycle();
        } else {
            bitmap = tempBitmap;
        }

        return bitmap;
    }

    /**
     * 将指定的图片文件按指定的宽高像素返回bitmap
     *
     * @param filePath
     * @param cwidth
     * @param cheight  如果些值为0,则图片按照cwidth指定的宽度等比例压缩
     * @return
     * @author: zj
     * @time: 2013-11-4下午1:15:05
     */
    public Bitmap compressPicToBitmap(String filePath, int cwidth, int cheight) {
        BitmapFactory.Options bfOptions = new BitmapFactory.Options();
        bfOptions.inJustDecodeBounds = true;
        Bitmap bmp = null;
        try {
            if (cwidth == 0 && cheight == 0) {
                bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                bfOptions.inJustDecodeBounds = false;
                bfOptions.inSampleSize = 1;
                bmp = BitmapFactory.decodeFile(filePath, bfOptions);
            } else {
                if (cheight == 0) {
                    //按比例压缩
                    bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                    bfOptions.inJustDecodeBounds = false;
                    int width = bfOptions.outWidth;
                    int height = bfOptions.outHeight;
                    int be = width / cwidth;
                    if (be <= 0) be = 1;
                    bfOptions.inSampleSize = be;
                    bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                } else {
                    bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                    bfOptions.inJustDecodeBounds = false;
                    int width = bfOptions.outWidth;
                    int height = bfOptions.outHeight;
                    int be = width * height / (cwidth * cheight);
                    if (be <= 0) be = 1;
                    bfOptions.inSampleSize = be / 2;
                    bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                }
            }


        } catch (OutOfMemoryError e) {
            if (bmp != null) {
                bmp.recycle();
                bmp = null;
            }
            // 提示系统，进行内存回收
            System.gc();
            //压缩图片重新加载
            compressPicToBitmap(filePath, cwidth - 10, cheight - 10);

        }
        return bmp;

    }

    /**
     * 将指定的图片文件按指定的宽高像素返回bitmap
     *
     * @param filePath
     * @return
     * @author: zj
     * @time: 2013-11-4下午1:15:05
     */
    public Bitmap compressPicToBitmap2(String filePath, int mk) {
        BitmapFactory.Options bfOptions = new BitmapFactory.Options();
        bfOptions.inJustDecodeBounds = true;
        Bitmap bmp = null;
        try {
            if (mk == 0) {
                bmp = BitmapFactory.decodeFile(filePath, bfOptions);
                bfOptions.inJustDecodeBounds = false;
                bfOptions.inSampleSize = 1;
                bmp = BitmapFactory.decodeFile(filePath, bfOptions);
            } else {
                int kb = (int) (new File(filePath).length() / 1024);
                int be = kb / mk;
                if (be <= 0) be = 1;
                double p = Math.sqrt(be);
                be = (int) Math.round(p);
                bfOptions.inJustDecodeBounds = false;
                bfOptions.inSampleSize = be;
                bmp = BitmapFactory.decodeFile(filePath, bfOptions);
            }


        } catch (OutOfMemoryError e) {
            if (bmp != null) {
                bmp.recycle();
                bmp = null;
            }
            // 提示系统，进行内存回收
            System.gc();
            //压缩图片重新加载
            compressPicToBitmap(filePath, mk);

        }
        return bmp;

    }

    /**
     * 如果传入的图片路径得不到图片返回Null
     *
     * @param pic
     * @param width  得到的图片的宽度
     * @param height 得到的图片的高度
     * @return drawable 或 null
     * @author: zj
     * @time: 2013-11-12下午1:34:12
     */
    public Drawable fileToDrawable(String pic, int width, int height) {
        //得到Bitmap
        Bitmap bitmap = compressPicToBitmap(pic, width, height);
        if (bitmap == null) return null;
        //得到drawable
        Drawable drawable = bitmapToDrawable(bitmap);

        return drawable;
    }


    /**
     * 压缩图片到指定的mk kb
     *
     * @param filePath
     * @return
     * @author: zj
     * @time: 2013-11-1下午3:49:25
     */
    public Bitmap compressPicToBitmap(String filePath, int mk) {
        if (mk == 0) mk = 80;
        Bitmap bmp = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.JPEG, mk, baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        int options = 100;
        while ((baos.toByteArray().length / 1024) > mk) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset();//重置baos即清空baos
            bmp.compress(CompressFormat.JPEG, options, baos);//这里压缩options%，把压缩后的数据存放到baos中
            options -= 10;//每次都减少5
        }
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm);//把ByteArrayInputStream数据生成图片
        return bitmap;

    }

    /**
     * 压缩图片到指定的mk kb
     *
     * @param filePath
     * @return
     * @author: zj
     * @time: 2013-11-1下午3:49:25
     */
    public Bitmap compressPicToBitmap3(String filePath, int mk) {
        if (mk == 0) mk = 80;
        long length = new File(filePath).length();
        long scale = mk / (length / 1024);
        if (scale >= 1) scale = 1;

        Bitmap bmp = BitmapFactory.decodeFile(filePath);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bmp.compress(CompressFormat.JPEG, (int) (scale * 100), baos);//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
        Bitmap bitmap = BitmapFactory.decodeStream(isBm);//把ByteArrayInputStream数据生成图片
        return bitmap;

    }

    /*
     * 得到图片字节流 数组大小
     * */
    public byte[] readStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        outStream.close();
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * 读取图片属性：旋转的角度
     *
     * @param path 图片绝对路径
     * @return degree旋转的角度
     */
    public int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    public AlertDialog selectedPhotodialog2(final Context context, final String picPath) {
        final Bitmap bitmap = picFileToBitmap(picPath);
        //判断要删除的图片的名字是否以HttpPicTag开头
        int num = picPath.lastIndexOf("/");
        //String picName = picPath.substring(num+1,picPath.length());


        LayoutInflater mInflater = LayoutInflater.from(context);
        View view = mInflater.inflate(R.layout.photo_item_show, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.photo_item_show_image);
        imageView.setImageBitmap(bitmap);

        AlertDialog.Builder adbuilder = new AlertDialog.Builder(context);
        adbuilder.setView(view);

        adbuilder.setNegativeButton(
                "取消",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(
                            DialogInterface dialog,
                            int which) {
                        if (bitmap != null) bitmap.recycle();
                    }

                });
        return adbuilder.show();
    }


    public AlertDialog selectedPhotodialog2(final Context context, final Drawable iconId) {
        final Bitmap bitmap = drawableToBitmap(iconId);
        //判断要删除的图片的名字是否以HttpPicTag开头

        LayoutInflater mInflater = LayoutInflater.from(context);
        View view = mInflater.inflate(R.layout.photo_item_show, null);
        ImageView imageView = (ImageView) view.findViewById(R.id.photo_item_show_image);
        imageView.setImageBitmap(bitmap);

        AlertDialog.Builder adbuilder = new AlertDialog.Builder(context);
        adbuilder.setView(view);

        adbuilder.setNegativeButton(
                "取消",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(
                            DialogInterface dialog,
                            int which) {
                        bitmap.recycle();
                    }

                });
        return adbuilder.show();
    }


    /**
     * 将不包含后缀.zip的文件加上后缀，如果inPath是一个目录，将会返回inPath的zip文件
     *
     * @param inPath
     * @return
     * @author: Administrator
     * @time: 2013-10-25上午10:15:36
     */
    public String toZipFileName(String inPath) {
        if (inPath.endsWith("/")) {
            inPath = inPath.substring(0, inPath.length() - 1);
        }
        return inPath + ".zip";
    }


    /**
     * 返回/sdcard/HLW_Pics/person/目录
     * @author: zj
     * @time: 2013-11-1上午10:02:45
     */
    public String refreshIdentityPic(Context context) {
        //保存拍身份证照片的路径
        String bpath = "HLW_Pics/person";
        //从资源id中获取图片文件夹地址
        IdentityPicPath = ContextUtils.getPicDirName(context, bpath);
        //System.out.println("IdentityPicPath: " + IdentityPicPath);

        //删除图片文件夹
        ContextUtils.DeleteFile(new File(IdentityPicPath));

        //刷新本地相册
        ContextUtils.refreshLocalPhotoAlbum(context, IdentityPicPath);

        return IdentityPicPath;
    }


    /**
     * 删除指定的文件夹数组中的所有文件夹
     *
     * @param deleteFiles
     * @author: zj
     * @time: 2013-11-18上午10:46:19
     */
    public void refreshIdentityPic(Context context, String[] deleteFiles) {

        for (int i = 0; i < deleteFiles.length; i++) {
            //删除图片文件夹
            ContextUtils.DeleteFile(new File(deleteFiles[i]));

            //刷新本地相册
            ContextUtils.refreshLocalPhotoAlbum(context, deleteFiles[i]);
        }
    }

    /**
     * 压缩文件夹dir下的图片，指定压缩后图片的大小为size左右kb
     *
     * @param dir
     * @param size
     * @return
     * @author: zj
     * @time: 2013-11-18上午9:55:40
     */
    public String[][] compressPicFiles(Context context, String dir, int size) {

        //保存拍身份证照片的路径
        String bpath = "VZPics/business/compress";
        //从资源id中获取图片文件夹地址
        String newDir = ContextUtils.getPicDirName(context, bpath);//"VZPics/business/compress/"

        String[][] f = null;
        //判断dir是一个文件夹还是一个文件的路径
        File file = new File(dir);
        char lastSymbol = newDir.charAt(IdentityPicPath.length() - 1);
        if (!String.valueOf(lastSymbol).equals("/"))
            newDir = newDir + "/";
        //创建一个存放压缩后文件的文件夹
        ContextUtils.makeDirs(newDir);

        if (file.isDirectory()) {
            //如果是一个文件夹就遍历这个文件夹下的所有图片文件，将文件的绝对路径存入一个数组中
            File[] childFile = file.listFiles();
            f = new String[2][childFile.length];
            f[0][0] = newDir;
            for (int i = 0; i < childFile.length; i++) {
                if (childFile[i].isDirectory()) continue;
                if (!isPicFile(childFile[i])) continue;
                Bitmap bitmap = compressPicToBitmap2(childFile[i].getAbsolutePath(), size);
                //将得到的压缩后的bitmap转成文件保存
                String fileName = newDir + childFile[i].getName();
                boolean boo = saveBitmap2file(bitmap, fileName);
                if (boo) {
                    //保存成功
                    f[1][i] = fileName;
                    bitmap.recycle();
                }
            }


        } else if (file.isFile()) {
            f = new String[2][1];
            f[0][0] = newDir;
            //如果是一个文件则直接进行图片压缩处理
            Bitmap bitmap = compressPicToBitmap2(file.getAbsolutePath(), size);
            //将得到的压缩后的bitmap转成文件保存
            String fileName = newDir + file.getName();
            boolean boo = saveBitmap2file(bitmap, fileName);
            if (boo) {
                //保存成功
                f[1][0] = fileName;
                bitmap.recycle();
            }
        }
        return f;
    }


    /**
     * 压缩文件夹dir下的图片，指定压缩后图片的大小为size左右kb
     *
     * @param dir
     * @param size
     * @param compressDir 压缩后的图片保存的文件夹
     * @return
     * @author: zj
     * @time: 2013-11-18上午9:55:40
     */
    public String[][] compressPicFiles(String dir, int size, String compressDir) {

        //从资源id中获取图片文件夹地址
        //String newDir = ContextUtils.getPicDirName(activity,compressDir);
        String newDir = compressDir;
        String[][] f = null;
        //判断dir是一个文件夹还是一个文件的路径
        File file = new File(dir);
        char lastSymbol = newDir.charAt(newDir.length() - 1);
        if (!String.valueOf(lastSymbol).equals("/"))
            newDir = newDir + "/";
        //创建一个存放压缩后文件的文件夹
        ContextUtils.makeDirs(newDir);

        if (file.isDirectory()) {
            //如果是一个文件夹就遍历这个文件夹下的所有图片文件，将文件的绝对路径存入一个数组中
            File[] childFile = file.listFiles();
            f = new String[2][childFile.length];
            f[0][0] = newDir;
            for (int i = 0; i < childFile.length; i++) {
                if (childFile[i].isDirectory()) continue;
                if (!isPicFile(childFile[i])) continue;
                Bitmap bitmap = compressPicToBitmap2(childFile[i].getAbsolutePath(), size);
                //将得到的压缩后的bitmap转成文件保存
                String fileName = newDir + childFile[i].getName();
                boolean boo = saveBitmap2file(bitmap, fileName);
                if (boo) {
                    //保存成功
                    f[1][i] = fileName;
                    bitmap.recycle();
                }
            }


        } else if (file.isFile()) {
            f = new String[2][1];
            f[0][0] = newDir;
            //如果是一个文件则直接进行图片压缩处理
            Bitmap bitmap = compressPicToBitmap2(file.getAbsolutePath(), size);
            //将得到的压缩后的bitmap转成文件保存
            String fileName = newDir + file.getName();
            boolean boo = saveBitmap2file(bitmap, fileName);
            if (boo) {
                //保存成功
                f[1][0] = fileName;
                bitmap.recycle();
            }
        }
        return f;
    }


    /**
     * 压缩文件夹dir下的图片，指定压缩后图片的大小为size左右kb
     *
     * @param dir
     * @param compressDir 压缩后的图片保存的文件夹
     * @return
     * @author: zj
     * @time: 2013-11-18上午9:55:40
     */
    public String[][] compressPicFiles(String dir, int width, int height, String compressDir) {

        //从资源id中获取图片文件夹地址
        //String newDir = ContextUtils.getPicDirName(activity,compressDir);
        String newDir = compressDir;
        String[][] f = null;
        //判断dir是一个文件夹还是一个文件的路径
        File file = new File(dir);
        char lastSymbol = newDir.charAt(newDir.length() - 1);
        if (!String.valueOf(lastSymbol).equals("/"))
            newDir = newDir + "/";
        //创建一个存放压缩后文件的文件夹
        ContextUtils.makeDirs(newDir);

        if (file.isDirectory()) {
            //如果是一个文件夹就遍历这个文件夹下的所有图片文件，将文件的绝对路径存入一个数组中
            File[] childFile = file.listFiles();
            f = new String[2][childFile.length];
            f[0][0] = newDir;
            for (int i = 0; i < childFile.length; i++) {
                if (childFile[i].isDirectory()) continue;
                if (!isPicFile(childFile[i])) continue;
                Bitmap bitmap = compressPicToBitmap(childFile[i].getAbsolutePath(), width, height);
                //将得到的压缩后的bitmap转成文件保存
                String fileName = newDir + childFile[i].getName();
                boolean boo = saveBitmap2file(bitmap, fileName);
                if (boo) {
                    //保存成功
                    f[1][i] = fileName;
                    bitmap.recycle();
                }
            }


        } else if (file.isFile()) {
            f = new String[2][1];
            f[0][0] = newDir;
            if (!isPicFile(file)) return f;
            //如果是一个文件则直接进行图片压缩处理
            Bitmap bitmap = compressPicToBitmap(file.getAbsolutePath(), 200, 0);
            //将得到的压缩后的bitmap转成文件保存
            String fileName = newDir + file.getName();
            boolean boo = saveBitmap2file(bitmap, fileName);
            if (boo) {
                //保存成功
                f[1][0] = fileName;
                bitmap.recycle();
            }
        }
        return f;
    }

    /**
     * 压缩图片file，指定压缩后图片的大小为width height
     *
     * @param file
     *  压缩后的图片保存的文件夹
     * @return
     * @author: zj
     * @time: 2013-11-18上午9:55:40
     */
    public String[][] compressPicFile(String file, int width, int height, String compressedName) {

        String[][] f = null;
        //判断dir是一个文件夹还是一个文件的路径
        File mfile = new File(file);

        if (mfile.isFile()) {
            String fileParentPath = mfile.getParent();

            char lastSymbol = fileParentPath.charAt(fileParentPath.length() - 1);
            if (!String.valueOf(lastSymbol).equals("/"))
                fileParentPath = fileParentPath + "/";

            f = new String[2][1];
            f[0][0] = fileParentPath;
            if (!isPicFile(mfile)) return f;
            //如果是一个文件则直接进行图片压缩处理
            Bitmap bitmap = compressPicToBitmap(mfile.getAbsolutePath(), width, height);
            //将得到的压缩后的bitmap转成文件保存
            String fileName = "";
            if (compressedName == null)
                fileName = fileParentPath + mfile.getName();
            else
                fileName = fileParentPath + compressedName;

            boolean boo = saveBitmap2file(bitmap, fileName);
            if (boo) {
                //保存成功
                f[1][0] = fileName;
                bitmap.recycle();
            }
        }
        return f;
    }

    /**
     * 判断某个文件是否是图片文件
     *
     * @return true表示是图片文件，false表示不是图片文件
     * @author: zj
     * @time: 2013-11-18下午2:25:11
     */
    public boolean isPicFile(File f) {
        //if(!f.exists())return false;
        int i = f.getName().lastIndexOf(".");
        if (i == -1) return false;
        String suffix = f.getName().substring(i + 1);
        //System.out.println("suffix :" + suffix);
        if (suffix.toLowerCase().contains("jpg") ||
                suffix.toLowerCase().contains("jpeg") ||
                suffix.toLowerCase().contains("png") ||
                suffix.toLowerCase().contains("gif") ||
                suffix.toLowerCase().contains("bmp")) {
            return true;
        }
        return false;
    }


    /**
     * 开启下载异步线程
     *
     * @param imageUrl 下载地址
     */
    public void DownloadImages(String dirPath, String imageUrl) {
        GetPicsFromInternet task = new GetPicsFromInternet(dirPath, imageUrl);
        task.execute(imageUrl);
    }

    /**
     * 根据传入的多个图片url地址并通过网络获取这些图片
     *
     * @param activity
     * @param dirPath  图片保存的文件夹绝对路径
     * @param urls
     */
    public void handlePicUrls(Activity activity, String dirPath, List<String> urls) {

        //清空
        picList.clear();
        //初始化占位图片
        for (int i = 0; i < urls.size(); i++) {
            //if(picList.contains(urls[i]))continue;
            picList.add(urls.get(i));

            DownloadImages(dirPath, urls.get(i));
        }


    }

    /**
     * urls[0] 下载好的图片的url;urls[1]对应url的下载好的图片的绝对路径
     *
     * @param urls
     * @author: zj
     * @time: 2013-11-21上午11:47:07
     */
    public void downloadOverOneFile(String[] urls) {
    }

    class GetPicsFromInternet extends AsyncTask<String, ImageView, String[]> {

        private String imageUrl;
        private String dirPath;
        private String fileName;

        private String[] urls = new String[2];

        public GetPicsFromInternet(String dirPath, String imageUrl) {
            super();
            this.dirPath = dirPath;
            this.imageUrl = imageUrl;
        }

        @Override
        protected String[] doInBackground(String... params) {
            imageUrl = params[0];
            // 在后台开始下载图片
            Bitmap bitmap = downloadBitmap(params[0]);
            Random random = new Random(10000);
            if (bitmap != null) {
                //创建文件夹
                ContextUtils.makeDirs(dirPath);
                // 图片下载完成后保存到本地
                fileName = dirPath + HttpPicTag + DateUtils.getLocalLongDate14() + "x" + random.nextInt() + ".jpg";
                saveBitmap2fileAfterClear(bitmap, fileName);
                //将url换成本地保存的图片地址
                if (picList.lastIndexOf(imageUrl) != -1) {
                    picList.set(picList.lastIndexOf(imageUrl), fileName);
                }
            }
            urls[0] = imageUrl;
            urls[1] = fileName;

            return urls;
        }

        @Override
        protected void onPostExecute(String[] picName) {
            super.onPostExecute(picName);
            //下载完成
            downloadOverOneFile(picName);
        }

        /**
         * 建立HTTP请求，并获取Bitmap对象。
         *
         * @param imageUrl 图片的URL地址
         * @return 解析后的Bitmap对象
         */
        private Bitmap downloadBitmap(String imageUrl) {
            Bitmap bitmap = null;
            HttpURLConnection con = null;
            try {
                URL url = new URL(imageUrl);
                con = (HttpURLConnection) url.openConnection();
                con.setConnectTimeout(5 * 1000);
                con.setReadTimeout(10 * 1000);
                con.setDoInput(true);
                //con.setDoOutput(true);
                con.setRequestMethod("GET");
                bitmap = BitmapFactory.decodeStream(con.getInputStream());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (con != null) {
                    con.disconnect();
                }
            }
            return bitmap;
        }

    }



}
